package com.dormms.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dormms.dto.UserRoleDto;

public class UserRoleInterceptor implements HandlerInterceptor{

	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		HttpSession session = arg0.getSession();
		UserRoleDto userRole = (UserRoleDto) session.getAttribute("userRoleDto");
		String url = arg0.getRequestURI();
		if(url.indexOf("logout.do") > 0) {
			session.removeAttribute("userRoleDto");
			session.invalidate();
			arg1.sendRedirect(arg0.getContextPath());
			return false;
		}
		if(userRole!=null && userRole.getRoleName() !=null && (url.indexOf(userRole.getRoleName()) > 0)) {
			return true;
		}
		arg1.sendRedirect(arg0.getContextPath());
		return false;
	}

}
